package com.genesis.web.controller;

import com.genesis.mall.common.Result;
import com.genesis.mall.config.MinioConfig;
import com.genesis.mall.config.RedisCache;

import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/aliyun/oss")
@Slf4j
public class commonController {

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.port}")
    private String port;

    @Value("${minio.bucketName}")
    private String bucketName;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;

    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private RedisCache redisCache;


    /* */

    /**
     * 文件上传
     *
     * @param
     * @return
     */
    @PostMapping("/upload")
    public Result<Map> upload(@RequestParam("photoFile") MultipartFile file) {
        InputStream inputStream = null;
        //创建Minio的连接对象
        MinioClient minioClient = getClient();
        String bucketName = minioConfig.getBucketName();

        try {
            inputStream = file.getInputStream();
            //判断文件存储的桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                //如果桶不存在则创建通
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());

            }
            //操作文件
            String fileName = file.getOriginalFilename();
            String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));
            redisCache.setCacheObject("name",objectName);

            //文件上传
            //由于使用的是SpringBoot与之进行集成 上传的时候拿到的是MultipartFile 需要通过输入输出流的方式进行添加
            PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)
                    .bucket(bucketName)
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(), file.getSize(), -1).build();
            minioClient.putObject(objectArgs);
            //封装访问的url给前端
            HashMap<String, Object> map = new HashMap<>();
           // map.put("fileName", "/" + bucketName + "/" + objectName);
            //url需要进行截取
            map.put("url", "http://"+minioConfig.getEndpoint() + ":" +8080 + "/aliyun/oss/download");
            return Result.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上传失败");
        } finally {
            //防止内存泄漏
            if (inputStream != null) {
                try {
                    inputStream.close(); // 关闭流
                } catch (IOException e) {
                    log.debug("inputStream close IOException:" + e.getMessage());
                }
            }
        }
    }

    /**
     * 免费提供一个获取Minio连接的方法
     * 获取Minio连接
     *
     * @return
     */

    private MinioClient getClient() {
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint("http://" + minioConfig.getEndpoint() + ":" + minioConfig.getPort())
                        .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                        .build();
        return minioClient;
    }

    @GetMapping("/download")
    public void download( HttpServletResponse response) {
        try {
            //获取minnio的客户端对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint("http://" + endpoint + ":" + port)
                    .credentials(accessKey, secretKey).build();
            String name = redisCache.getCacheObject("name");
            //获取minio服务器中的数据
            InputStream stream = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(name).build());


            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            //设置响应的文件类型
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = stream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            stream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @GetMapping("/policy")
    public Result<Map> policy(@RequestParam("photoFile") MultipartFile file) {
        InputStream inputStream = null;
        //创建Minio的连接对象
        MinioClient minioClient = getClient();
        String bucketName = minioConfig.getBucketName();

        try {
            inputStream = file.getInputStream();
            //判断文件存储的桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                //如果桶不存在则创建通
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());

            }
            //操作文件
            String fileName = file.getOriginalFilename();
            String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));
            redisCache.setCacheObject("name",objectName);

            //文件上传
            //由于使用的是SpringBoot与之进行集成 上传的时候拿到的是MultipartFile 需要通过输入输出流的方式进行添加
            PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)
                    .bucket(bucketName)
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(), file.getSize(), -1).build();
            minioClient.putObject(objectArgs);
            //封装访问的url给前端
            HashMap<String, Object> map = new HashMap<>();
            // map.put("fileName", "/" + bucketName + "/" + objectName);
            //url需要进行截取
            map.put("url", "http://"+minioConfig.getEndpoint() + ":" +8080 + "/aliyun/oss/download");
            return Result.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上传失败");
        } finally {
            //防止内存泄漏
            if (inputStream != null) {
                try {
                    inputStream.close(); // 关闭流
                } catch (IOException e) {
                    log.debug("inputStream close IOException:" + e.getMessage());
                }
            }
        }
    }

}